package org.yun.redpack;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.yun.biz.dao.DrawRecordRepository;
import org.yun.biz.dao.RedPackRepository;
import org.yun.biz.dto.TinyRedPack;
import org.yun.biz.model.DrawRecord;
import org.yun.biz.model.RedPack;
import org.yun.util.*;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.*;

import static org.yun.constants.RedisConstant.RED_PACK;
import static org.yun.util.CommonUtil.*;
import static org.yun.util.RedisUtil.POP_GRAB_RED_SCRIPT;

/**
 * @ProjectName: no-concurrent
 * @ClassName: PreLoadStrategy
 * @Description: 限流+mysql
 * @Author: liyunfeng31
 * @Date: 2020/10/4 23:22
 */
@SuppressWarnings("UnstableApiUsage")
@Slf4j
@Component
public class PreLoadImpl implements RedPackService {


    @Resource
    private RedisUtil redisUtil;

    @Resource
    private RedPackRepository redPackDao;

    @Resource
    private DrawRecordRepository drawRecordDao;


    @Transactional(rollbackOn = Exception.class)
    @Override
    public Long createRedPack(RedPack redPack, Long userId) {
        // 参数校验
        CommonUtil.checkRedPackParam(redPack);
        // 根据支付凭证校验是否合法
        redPackDao.save(redPack);
        List<DrawRecord> records = RandomRedUtil.allocateRedPack(redPack);
        List<String> tiny = new ArrayList<>();
        drawRecordDao.saveAll(records);
        records.forEach(x-> tiny.add(JSON.toJSONString(new TinyRedPack(x.getTinyRdId().toString(),x.getAmount().toString()))));
        redisUtil.lpush(RED_PACK + redPack.getRedPackId(), tiny);
        // todo 群通知
        return redPack.getRedPackId();
    }



    @Override
    public boolean clickRedPack(Long redPackId, Long userId) {
        return redisUtil.lLen(RED_PACK + redPackId) > 0;
    }

    @Override
    public Integer grabRedPack(Long redPackId, Long userId) {
        Long result = redisUtil.executeScript(POP_GRAB_RED_SCRIPT, keys(redPackId), userId.toString());
        return result.intValue() ;
    }


}
